package com.example.elm.Messages

import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.elm.Public.MessageInfo
import com.example.elm.R
import com.example.elm.databinding.MessagesMainBinding
import android.app.AlertDialog
import android.util.Log
import android.widget.Toast
import com.example.elm.Public.MyApplication
import okhttp3.OkHttpClient
import okhttp3.Request
import org.xmlpull.v1.XmlPullParser
import org.xmlpull.v1.XmlPullParserFactory
import java.io.BufferedReader
import java.io.DataOutputStream
import java.io.InputStreamReader
import java.io.StringReader
import java.net.HttpURLConnection
import java.net.URL
import java.net.URLEncoder
import kotlin.concurrent.thread

class MessagesMainFragment:Fragment() {
    private var messageList1 = ArrayList<MessageInfo>()
    private var messageList2 = ArrayList<MessageInfo>()
    private var messageList3 = ArrayList<MessageInfo>()
    private lateinit var binding: MessagesMainBinding
    private val server_ip = MyApplication.serverIp
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        //初始化
        ReadMessageByXml()
        // 使用 View Binding 绑定布局
        binding = MessagesMainBinding.inflate(inflater, container, false)
        return binding.root
    }
    // onViewCreated 负责视图相关的数据初始化和操作
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        // 布局管理器
        val layoutManager1 = LinearLayoutManager(requireContext())
        binding.message1.layoutManager = layoutManager1
        val adapter1 = MessageAdapter(messageList1)
        binding.message1.adapter = adapter1

        //initMessageList2()
        val layoutManager2 = LinearLayoutManager(requireContext())
        binding.message2.layoutManager = layoutManager2
        val adapter2 = MessageAdapter(messageList2)
        binding.message2.adapter = adapter2

        //initMessageList3()
        val layoutManager3 = LinearLayoutManager(requireContext())
        binding.message3.layoutManager = layoutManager3
        val adapter3 = MessageAdapter(messageList3)
        binding.message3.adapter = adapter3

        if(messageList1.isEmpty()) {
            binding.messageSetting.setOnClickListener {
                val intent = Intent(activity, Message_SettingActivity::class.java)
                startActivity(intent)
            }
            binding.messageDelete.setOnClickListener {
                // 创建一个对话框
                val builder = AlertDialog.Builder(context)
                builder.setMessage("暂无消息")
                // 显示对话框
                builder.show()
            }
        }
        else {
            // 设置点击事件，启动 Message_AllActivity
            binding.messageAll.setOnClickListener {
                val intent = Intent(activity, Message_AllActivity::class.java)
                startActivity(intent)
            }
            // 设置点击事件，启动 Message_SettingActivity
            binding.messageSetting.setOnClickListener {
                val intent = Intent(activity, Message_SettingActivity::class.java)
                startActivity(intent)
            }
            binding.messageDelete.setOnClickListener {
                // 创建一个对话框
                val builder = AlertDialog.Builder(context)
                builder.setTitle("确认清空消息列表吗")
                    .setMessage("操作后，将清空全量平台通知与聊天动态，请谨慎操作")
                    .setPositiveButton("清空") { dialog, which ->
                        update()
                        delete_all_message()
                    }
                    .setNegativeButton("取消") { dialog, which ->
                        dialog.dismiss()
                    }

                // 显示对话框
                builder.show()
            }
        }
    }
    // 将每行layout文件，代码与控件关联
    private class ViewHolder(view:View): RecyclerView.ViewHolder(view) {
        val image = view.findViewById<ImageView>(R.id.imageView)
        val name = view.findViewById<TextView>(R.id.tvName)
        val date = view.findViewById<TextView>(R.id.tvDate)
        val message = view.findViewById<TextView>(R.id.tvMessage)
    }
    // 适配器，填充数据
    private class MessageAdapter(val MessageList:ArrayList<MessageInfo>): RecyclerView.Adapter<ViewHolder> () {
        private val server_ip = MyApplication.serverIp
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
            val view = LayoutInflater.from(parent.context).inflate(
                R.layout.message_elem, parent, false)
            return ViewHolder(view)
        }

        override fun onBindViewHolder(holder: ViewHolder, position: Int) {
            val messageInfo = MessageList[position]
            val imageResId = holder.itemView.context.resources.getIdentifier(
                messageInfo.image, "drawable", holder.itemView.context.packageName
            )
            if (imageResId != 0) {
                holder.image.setImageResource(imageResId)
            } else {
                holder.image.setImageResource(R.drawable.m1)
            }
            holder.name.text = messageInfo.name
            holder.date.text = messageInfo.date
            holder.message.text = messageInfo.message
            Log.d("信息holder", "${messageInfo.message}")
            holder.itemView.setOnClickListener {
                if(messageInfo.name == "亲~有一份惊喜在等待您" || messageInfo.name == "你附近有趋势爆款!"){
                    val intent = Intent(holder.itemView.context, Message_AllActivity::class.java)
                    holder.itemView.context.startActivity(intent)
                }
                else {
                    val intent = Intent(holder.itemView.context, Message_TalkActivity::class.java)
                    intent.putExtra("left_name", messageInfo.name)
                    intent.putExtra("left_message", messageInfo.message)
                    intent.putExtra("left_image", messageInfo.image)
                    holder.itemView.context.startActivity(intent)
                }
            }
            holder.itemView.setOnLongClickListener {
                if(messageInfo.name != "亲~有一份惊喜在等待您" && messageInfo.name != "你附近有趋势爆款!"){
                    val builder = AlertDialog.Builder(holder.itemView.context)
                    builder.setMessage("确认删除这条消息吗")
                        .setPositiveButton("删除") { dialog, which ->
                            delete_message(messageInfo.name)
                            notifyDataSetChanged()
                        }
                        .setNegativeButton("取消") { dialog, which ->
                            dialog.dismiss()
                        }

                    // 显示对话框
                    builder.show()
                }
                true
            }
        }
        override fun getItemCount(): Int {
            return MessageList.size
        }

        fun delete_message(name: String){
            val del_goods_jsp = "http://$server_ip:8080/Message/delete_Message.jsp"
            thread {
                var connection : HttpURLConnection? = null
                try {
                    val response = StringBuilder()
                    val url = URL(del_goods_jsp)
                    connection = url.openConnection() as HttpURLConnection
                    connection.connectTimeout = 8000 //  连接 超时
                    connection.readTimeout = 8000 // read 超时时间
                    connection.requestMethod = "POST"
                    val output = DataOutputStream(connection.outputStream)
                    output.writeBytes("name=$name")
                    val input = connection.inputStream
                    //  读取输入流，类似与文件流
                    val reader = BufferedReader(InputStreamReader(input))
                    reader.use{
                        reader.forEachLine {
                            response.append(it)
                        }
                    }

                    val index = MessageList.indexOfFirst { it.name == name }
                    if (index != -1) { // 确保找到了对应的项
                        MessageList.removeAt(index) // 移除该项
                    }

                    showResponse(response.toString())
                }
                catch (e: Exception){
                    e.printStackTrace()
                }
                finally {
                    connection?.disconnect()
                }
            }
        }
        fun showResponse(response:String){
            Log.d("删除成功",response)
        }

    }

    private fun update() {
        binding.MessageEmpty.visibility = View.VISIBLE
        binding.MessageHave.visibility = View.GONE
        binding.messageSetting.setOnClickListener {
            val intent = Intent(activity, Message_SettingActivity::class.java)
            startActivity(intent)
        }
        binding.messageDelete.setOnClickListener {
            // 创建一个对话框
            val builder = AlertDialog.Builder(context)
            builder.setMessage("暂无消息")
            // 显示对话框
            builder.show()
        }
    }

    // 通过xml读取
    fun ReadMessageByXml(){
        val message_all = "http://$server_ip:8080/Message/get_all_Message_xml.jsp"
        thread {
            try{
                val client = OkHttpClient()
                val request: Request = Request.Builder()
                    .url(message_all)
                    .build()
                val response = client.newCall(request).execute()
                val responseData = response.body?.string()
                requireActivity().runOnUiThread {
                    if (!responseData.isNullOrEmpty()) {
                        binding.MessageEmpty.visibility = View.GONE
                        binding.MessageHave.visibility = View.VISIBLE
                        parseXml(responseData.toString().trim())
                        Log.d("信息","有数据")
                    } else {
                        Log.d("信息","没有数据")
                    }
                }

            }
            catch (e: Exception){
                e.printStackTrace()
                Log.d("信息","网络问题")
            }
        }
    }

    // 解析xml
    fun parseXml(xmlStr: String): String{
        try {
            val factory = XmlPullParserFactory.newInstance()
            val xmlPullPaser = factory.newPullParser()
            // 设置xml解析器的输入
            xmlPullPaser.setInput(StringReader(xmlStr))
            messageList1.clear()
            messageList2.clear()
            messageList3.clear()
            var eventType = xmlPullPaser.eventType//  事件类型
            var image = ""
            var name = ""
            var date = ""
            var message = ""
            var idStr = ""
            while(eventType != XmlPullParser.END_DOCUMENT){
                val nodeName = xmlPullPaser.name
                // builder.append("${nodeName}--")
                when(eventType) {
                    // 标签开始
                    XmlPullParser.START_TAG -> {
                        when (nodeName) {
                            "name" -> name = xmlPullPaser.nextText()
                            "image" -> image = xmlPullPaser.nextText()
                            "message" -> message  = xmlPullPaser.nextText()
                            "date" -> date = xmlPullPaser.nextText()
                            "id" -> idStr  = xmlPullPaser.nextText()
                        }
                    }
                    // 标签结束
                    XmlPullParser.END_TAG -> {
                        if ("Message" == nodeName) {
                            if(idStr.toIntOrNull() == 1) {
                                messageList1.add(
                                    MessageInfo(
                                        image,
                                        name,
                                        date,
                                        message,
                                    )
                                )
                                Log.d("信息","有数据1")
                            }
                            if(idStr.toIntOrNull() == 2) {
                                messageList2.add(
                                    MessageInfo(
                                        image,
                                        name,
                                        date,
                                        message,
                                    )
                                )
                                Log.d("信息","有数据2")
                            }
                            if(idStr.toIntOrNull() == 3) {
                                messageList3.add(
                                    MessageInfo(
                                        image,
                                        name,
                                        date,
                                        message,
                                    )
                                )
                                Log.d("信息","有数据3")
                            }
                        }
                    }
                }
                eventType = xmlPullPaser.next() //  读取下一个，进行遍历
            }
            if (isAdded) {
                requireActivity().runOnUiThread{
                    binding.message1.adapter?.notifyDataSetChanged()
                    binding.message2.adapter?.notifyDataSetChanged()
                    binding.message3.adapter?.notifyDataSetChanged()
                }
            }
        }
        catch (e: Exception){
            e.printStackTrace()
        }
        return ""
    }


    fun delete_all_message() {
        val del_all_message_jsp = "http://$server_ip:8080/Message/delete_all_Message.jsp"
        thread {
            var connection : HttpURLConnection? = null
            try {
                val response = StringBuilder()
                val url = URL(del_all_message_jsp)
                connection = url.openConnection() as HttpURLConnection
                connection.connectTimeout = 8000 //  连接 超时
                connection.readTimeout = 8000 // read 超时时间
                connection.requestMethod = "POST"
                val output = DataOutputStream(connection.outputStream)
                output.writeBytes("")
                val input = connection.inputStream
                //  读取输入流，类似与文件流
                val reader = BufferedReader(InputStreamReader(input))
                reader.use{
                    reader.forEachLine {
                        response.append(it)
                    }
                }
                messageList1.clear()
                messageList2.clear()
                messageList3.clear()

                showResponse(response.toString())
            }
            catch (e: Exception){
                e.printStackTrace()
            }
            finally {
                connection?.disconnect()
            }
        }
    }
    fun showResponse(response:String){
        Log.d("全部数据删除成功",response)
    }
}